﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;

namespace WebApp.Controllers
{
    public class SearchController : ApplicationController
    {
        public ActionResult People()
        {
            String authToken = HttpContext.Session["authToken"].ToString();
            String query = Request.QueryString["query"].ToString();
            if (query == null || query.Equals(""))
            {
                return new RedirectResult(Request.UrlReferrer.ToString());
            }
            Search<Person.Ref> search = new Search<Person.Ref>(
                Search<Person.Ref>.Type.User, new Person.Factory());
            List<Person.Ref> results = search.PerformSearch(query, authToken);
            ViewData["Model"] = results;
            ViewData["TitleFragment"] = "Search &quot;" + query + "&quot;";
            ViewData["Query"] = query;
            return View("Search");
        }

        /// <summary>
        /// Called before any of the actions are taken
        /// </summary>
        /// <param name="context"></param>
        override protected void OnActionExecuting(
            ActionExecutingContext context)
        {
            // If we don't have an auth token, we need to send the user to the
            // login page
            try
            {
                if (HttpContext.Session["authToken"] == null)
                {
                    context.Result = new RedirectResult("/");
                }
            }
            catch (Exception e)
            {
                context.Result = new RedirectResult("/");
            }
            base.OnActionExecuting(context);
        }
    }
}
